package com.sign2024.sign2024core.common.exeception;

import com.sign2024.sign2024core.common.CommonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理验证异常
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult valiateException(ConstraintViolationException ex) {
        String info = "";

        // 获取对应的迭代器
        Iterator<ConstraintViolation<?>> iterator = ex.getConstraintViolations().iterator();
        if (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            // 获取异常信息
            info = next.getMessage();
        }
        return CommonResult.error(info);
    }

    // 针对自定义异常，进行处理
    @ExceptionHandler(CommonException.class)
    public CommonResult commonExeceptionHandler(CommonException e) {

        System.out.println(e.getMsg());

        return CommonResult.error(e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult exeptionHandler(Exception e) {
        // 一般在异常类中，将捕获的异常存储到日志信息中
        // 当前系统中，打印日志
        e.printStackTrace();

        return CommonResult.error("未知异常");
    }
}
